package edu.yuhf.streamdemo;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.IntBinaryOperator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class OperationExample {

    public void lambdaProblem(){
        int[] temp = {0};
        IntStream.range(1,10).forEach(value->{
            temp[0] += value;
        });
        System.out.println(temp[0]);
    }

    public void reduceOperation(){
        //1，生成一个序列流
        var intStream = IntStream.rangeClosed(1,100);
        //2，将100个数进行累加操作
        //IntBinaryOperator ibo = (value1, value2)->value1+value2;    //利用lambda表达创建一个函数

        //IntBinaryOperator ibo = (value1,value2)->value1+value2;
        //以上代码可以进一步缩写成如下：
        IntBinaryOperator ibo = Integer::sum;

        System.out.println(ibo.applyAsInt(1,2));
        var sum = intStream.reduce(0, ibo);
        System.out.println(sum);
    }

    public void buildOperation(){
    }

    public void streamOperation(){
        String[] arrays={"java","javascript","python","c","html","css","java","c++","c#"};
        //1，把数组转化成流
        Stream<String> stream0 = Stream.of(arrays);  //把数组看成单个值的组合
        //2,去重
        Stream<String> stream1 = stream0.distinct();
        //3,过滤,把h开头的滤掉（新建类的方式实现）
        StartWithH startWithH = new StartWithH();   //创建一个类，该类的对象将成为filter的参数
        Stream<String> stream2 = stream1.filter(startWithH);
        //4，映射，改成大写字母（匿名内部类的方式实现）
        Stream<String> stream3 = stream2.map(String::toUpperCase);
        //4，规约操作，把流转换成集合
        List<String> list = stream3.collect(Collectors.toList());
        //5，打印出集合中的数据（使用lambda表达式实现）
        //在ArrayList中可以直接使用forEach()方法，因为Iterable中实现了该，但是其他的流式操作都不能使用。
        list.forEach(System.out::println);
    }

    public void compareOperation(){
        String[] arrays={"java","javascript","python","c","html","css","java","c++","c#"};
        Arrays.sort(arrays, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return 0;
            }
        });
        Arrays.stream(arrays).forEach(System.out::println);
    }

}
